package com.jic.order.task;

import com.alibaba.fastjson.JSONObject;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.order.api.SettlementApi;
import com.jic.order.request.base.OrderSyncRequest;
import com.jic.order.service.OrderGoodsService;
import com.jic.order.service.OrderParentService;
import com.jic.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 清结算调度
 */
@Component
@Slf4j
public class SettlementServiceTask {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderParentService orderParentService;
    @Autowired
    private ManagerMerchantApi managerMerchantApi;
    @Autowired
    private SettlementApi settlementApi;
    @Autowired
    private OrderGoodsService orderGoodsService;

    /**
     * 每天凌晨00点 扫描可结算的订单
     */
    @Scheduled(cron = "0 00 00 * * ?")
    // @Scheduled(fixedDelay = 10 * 60 * 1000)
    @Async("asyncServiceExecutor")
    public void updateSettlement() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<JSONObject> merchants = managerMerchantApi.getMerchantToSett();
        String ids = "";
        for(JSONObject merchant:merchants){
            if(StringUtils.isEmpty(merchant.getString("merchant_code"))){
                continue;
            }
            JSONObject param = new JSONObject();
            String merchant_code = merchant.getString("merchant_code");
            Integer billing_cycle =  merchant.getInteger("billing_cycle");
            param.put("merchant_code",merchant_code);
            param.put("billing_cycle",billing_cycle);
            param.put("now",simpleDateFormat.format(new Date()));
            //查询商户维度订单判断是否满足清结算(t+n)
            List<JSONObject> shOrders = orderGoodsService.querySettOrder(param);
            for(JSONObject order:shOrders){
                ids += order.getLongValue("id")+",";
            }
        }
        JSONObject param = new JSONObject();
        if(!StringUtils.isEmpty(ids)){
            ids = ids.substring(0,ids.length()-1);
            param.put("ids",ids);
            param.put("third_party_flag",2);
            orderService.updateOrderSettlement(param);
        }
        param.clear();
        param.put("now",simpleDateFormat.format(new Date()));
        ids = "";
        List<JSONObject> orders =  orderGoodsService.querySettOrderByPay(param);
        for(JSONObject order:orders){
            ids += order.getLongValue("id");
        }
        if(!StringUtils.isEmpty(ids)){
            ids = ids.substring(0,ids.length()-1);
            param.put("ids",ids);
            param.put("settlement_flag",2);
            orderService.updateOrderSettlement(param);
        }
    }



    /**
     * 每天凌晨01点
     */
    @Scheduled(cron = "0 00 01 * * ?")
   // @Scheduled(fixedDelay = 10 * 60 * 1000)
    @Async("asyncServiceExecutor")
    public void settlementTimerTask() {
        List<JSONObject> merchants = managerMerchantApi.getMerchantToSett();
        JSONObject param = new JSONObject();
        param.put("settlement_flag",1);
        List<JSONObject> mordersAll = orderParentService.querySettList(param);
        if(mordersAll==null || mordersAll.size()<0){
            return;
        }
        log.info("同步订单大小{}",mordersAll.size());
        //平台维度
        settlementTimerTask(mordersAll,true,null);
        String id = "";
        //修改订单状态为已结算
        for(JSONObject order: mordersAll){
            id+=order.getLong("id")+",";
        }
        id = id.substring(0,id.length()-1);
        param.put("id",id);
        param.put("settlement_flag",2);
        orderParentService.updateSettlementStatus(param);
        //商户维度
        for(JSONObject merchant:merchants){
            if(StringUtils.isEmpty(merchant.getString("merchant_code"))){
                continue;
            }
            param.clear();
            String merchant_code = merchant.getString("merchant_code");
            Integer billing_cycle =  merchant.getInteger("billing_cycle");
            param.put("merchant_code",merchant_code);
            param.put("third_party_flag",1);
            param.put("billing_cycle",billing_cycle);
            List<JSONObject> shMorders = orderParentService.querySettList(param);
            settlementTimerTask(shMorders,false,merchant);
            String shId="";
            for(JSONObject order: mordersAll){
                shId+=order.getLong("id")+",";
            }
            shId = shId.substring(0,shId.length()-1);
            param.put("id",shId);
            param.put("third_party_flag",2);
            orderParentService.updateSettlementStatus(param);
        }
    }

    public void settlementTimerTask(List<JSONObject> mOrders,boolean pushSum,JSONObject merchant){
        //付款金额(+快递费)
        BigDecimal actual_pay_total_amount = new BigDecimal("0");
        //优惠金额
        BigDecimal discount_total_amount = new BigDecimal("0");
        //销售总金额
        BigDecimal sale_total_amount = new BigDecimal("0");
        //购买金额
        BigDecimal buy_total_amount = new BigDecimal("0");
        BigDecimal wxMoney = new BigDecimal("0");
        BigDecimal wzMoney = new BigDecimal("0");
        BigDecimal third_party_price = new BigDecimal("0");
        //手续费
        BigDecimal fee = new BigDecimal("0");

        for(JSONObject mOrder:mOrders){
            Integer order_status = mOrder.getInteger ("order_status");
            BigDecimal fk_base = mOrder.getBigDecimal("actual_pay_total_amount");
            if(!pushSum){
                switch (order_status){
                    case 5:actual_pay_total_amount = actual_pay_total_amount.add(fk_base);
                    case 6:actual_pay_total_amount = actual_pay_total_amount.add(fk_base);
                    case 10:actual_pay_total_amount = actual_pay_total_amount.add(fk_base);
                    case 9:actual_pay_total_amount = actual_pay_total_amount.subtract(fk_base);
                }
            }else {
                if(9==order_status){
                    continue;
                }
                actual_pay_total_amount = actual_pay_total_amount.add(fk_base);
                discount_total_amount = discount_total_amount.add(mOrder.getBigDecimal("discount_total_amount"));
                sale_total_amount = sale_total_amount.add(mOrder.getBigDecimal("sale_total_amount"));
                third_party_price = third_party_price.add(mOrder.getBigDecimal("third_party_price"));
                Integer payment = mOrder.getInteger ("payment");
                switch (payment){
                    //微信
                    case 3: wxMoney = wxMoney.add(fk_base);break;
                    default:wzMoney = wzMoney.add(fk_base);break;
                }
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        fee = buy_total_amount.subtract(third_party_price);
        String orderId = UUID.randomUUID().toString().replaceAll("-","");
        Long times = Long.valueOf(simpleDateFormat.format(new Date()));
        OrderSyncRequest orderSyncRequest = new OrderSyncRequest();
        orderSyncRequest.setOrderId(orderId);
        orderSyncRequest.setFee(new BigDecimal("0"));
        orderSyncRequest.setQuantity(1);
        orderSyncRequest.setStatus(0);
        orderSyncRequest.setOriginalOrderId(orderId);
        orderSyncRequest.setCardId(orderId);
        orderSyncRequest.setOrderType(0);
        orderSyncRequest.setAmount(third_party_price);
        orderSyncRequest.setFee(fee);
        orderSyncRequest.setPurchaser("wz");
        orderSyncRequest.setSupplier("member");
        orderSyncRequest.setOrderFinishTime(times);
        orderSyncRequest.setMsgType("1301C003");
        //商城维度
        if(pushSum){
            //1.推送微信
            orderSyncRequest.setIncome(wxMoney);
            toSend(orderSyncRequest,0,null);
            //2.推送微众
            orderSyncRequest.setIncome(wxMoney);
            toSend(orderSyncRequest,1,null);
            //4.同步优惠券以及积分
            orderSyncRequest.setIncome(discount_total_amount);
            toSend(orderSyncRequest,3,null);
        }else{//商户维度推送收单
            orderSyncRequest.setIncome(actual_pay_total_amount);
            toSend(orderSyncRequest,4,merchant);
        }
    }
    private void toSend(OrderSyncRequest orderSyncRequest,Integer type,JSONObject merchant){
        try{
            settlementApi.listOrderSync(orderSyncRequest);
            saveSettlementRecord(true,type,merchant);
        }catch (Exception e){
            log.warn("订单同步失败{}",type);
            saveSettlementRecord(false,type,merchant);
        }
    }
    private void saveSettlementRecord(boolean success,Integer type,JSONObject merchant){
        JSONObject param = new JSONObject();
        param.put("type",type);
        if(null!=merchant){
            param.put("merchant_id", merchant.getLongValue("id"));
        }
        param.put("settlement_date",new Date());
        param.put("status",0);
        if(success){
            param.put("status",1);
        }
        param.put("create_time",new Date());
        param.put("update_time",new Date());
        orderService.insertOrderSettlement(param);
    }

    public static void main(String[] args) {
        String id = "1,";
        id = id.substring(0,id.length()-1);
        System.out.println(id);
    }

}
